<?php
namespace app\admin\controller;

use think\Controller;
use think\Loader;

class Ouser extends Controller
{
    public function index()
    {
        $keyword = input('get.keyword');
        if (isset($keyword) && trim($keyword) != ''){
            $warehouse_list = db('warehouse')->where('warehouse','like','%'.$keyword.'%')->paginate(12);
        }else {
            $warehouse_list = db('warehouse')->paginate(12);
        }
        $page = $warehouse_list->render();
        $this->assign('page',$page);
        $this->assign('warehouse_list',$warehouse_list);
        return $this->fetch('index');
    }
    public function export_users()
    {
        $warehouse_id = input('get.warehouse_id');
        $warehouse_name = input('post.warehouse_name');
        $ouser_data = db('ouser')->where('warehouse_id',$warehouse_id)->field(['id','user_name','created'])->select();
        foreach ($ouser_data as $ok => &$ov){
            $ov['created'] = date('Y-m-d H:i:s',$ov['created']);
        }
        $excel_header = array('ID','用户名','创建时间');
        $export_users = $this->write_excel($excel_header,$ouser_data,$warehouse_name.'普通用户导出表',ROOT_PATH.'Uploads'.DS.'export',true);
    }
    
    
    /**
     * 数据导出
     * @param array $title   标题行名称
     * @param array $data   导出数据
     * @param string $fileName 文件名
     * @param string $savePath 保存路径
     * @param $type   是否下载  false--保存   true--下载
     * @return string   返回文件全路径
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function write_excel($title=array(), $data=array(), $fileName='', $savePath='./', $isDown=false,$sheet_name='sheet1'){
        Loader::import('office.phpexcel.PHPExcel');
        Loader::import('office.phpexcel.PHPExcel.IOFactory');
        $objPHPExcel = new \PHPExcel();
    
        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
    
        $objPHPExcel->getActiveSheet(0)->setTitle($sheet_name);   //设置sheet名称
        $_row = 1;   //设置纵向单元格标识
        if($title){
            $_cnt = count($title);
            $objPHPExcel->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出时间：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容
            $_row++;
            $i = 0;
            foreach($title AS $v){   //设置列标题
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
                $i++;
            }
            $_row++;
        }
    
        //填写数据
        if($data){
            $i = 0;
            foreach($data AS $_v){
                $j = 0;
                foreach($_v AS $_cell){
                    $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
                    $j++;
                }
                $i++;
            }
        }
    
        //文件名处理
        if(!$fileName){
            $fileName = uniqid(time(),true);
        }
    
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
//         $objWrite = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
        if($isDown){   //网页下载
            header('pragma:public');
            header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$fileName.'.xls"');
            header("Content-Disposition:attachment;filename=$fileName.xls");
            $objWriter->save('php://output');
            exit();
        }
    
        $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
        $_savePath = $savePath.$_fileName.'.xls';
        $objWriter->save($_savePath);
    
        return $savePath.$fileName.'.xls';
    }
    
    //exportExcel(array('姓名','年龄'), array(array('a',21),array('b',23)), '档案', './', true);
  
    
    public function import_users()
    {
        $result = array('err' => '1','content' => '');
        $warehouse_id = input('get.warehouse_id');
        $warehouse_id = urldecode($warehouse_id);
        if (!$warehouse_id){
            $result['content'] = '参数错误！';
            return json_encode($result);
        }
        $users_excel = request()->file('import_users');
        $users_excel_info = $users_excel->getInfo();
        $users_excel_title = $users_excel_info['name'];
        $users_excel_title = iconv('utf-8', 'gb2312', $users_excel_title);
        $info = $users_excel->validate(['ext' => 'xls,xlsx'])->move(ROOT_PATH.'Uploads'.DS.'users',$users_excel_title);
        if ($info->getError()){
            $result['content'] = '上传失败';
            return json_encode($result);
        }
        $excle_file = $info->getSaveName();
        $excle_data = $this->read_excle(ROOT_PATH.'Uploads'.DS.'users'.DS.$excle_file);
        $ouser = model('Ouser');
        $import_users = $ouser->import_users((array)$excle_data,$warehouse_id);
        unset($info);
        unlink(ROOT_PATH.'Uploads'.DS.'users'.DS.$excle_file);
        if ($import_users == false){
            $result['content'] = '导入用户失败！';
            return json_encode($result);
        }
        $result['err'] = '0';
        $result['content'] = '导入用户成功！';
        return json_encode($result);
    }
    
    /**
     * 读取Excel函数
     * Excel模板须从第二行读起
     * @param unknown $excle_file
     */
    public function read_excle($excle_file)
    {
        Loader::import('office.phpexcel.PHPExcel');
        Loader::import('office.phpexcel.PHPExcel.PHPExcel_IOFactory');
        Loader::import('office.phpexcel.PHPExcel.PHPExcel_Cell');
        $file_ext = pathinfo($excle_file,PATHINFO_EXTENSION);
        if ($file_ext == 'xls'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }elseif ($file_ext == 'xlsx'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objPHPExcel = $objReader->load($excle_file);
        $excel_content = $objPHPExcel->getsheet(0)->toArray(); 
        array_shift($excel_content);
        array_shift($excel_content);
        return $excel_content;
    }
    
   
    
    public function save_warehouse()
    {
        $warehouse_id = input('get.warehouse_id');
        $keyword = input('get.keyword');
        $warehouse = db('warehouse')->where('id',$warehouse_id)->find();
        if ($keyword == '' || $keyword == false){
            $ouser_list = db('ouser')->where('warehouse_id',$warehouse_id)->paginate(15,false,['query' => request()->param()]);
        }else {
        	$ouser_list = db('ouser')->where('warehouse_id',$warehouse_id)->where('user_name','like','%'.$keyword.'%')->paginate(15,false,['query' => request()->param()]);
//             $ouser_list = db('ouser')->where('warehouse_id',$warehouse_id)->where('user_name','like','%'.$keyword.'%')->paginate(15,false,['query'=>request()->param()]);
        }
        $page = $ouser_list->render();
        $ouser_list = $ouser_list->toArray();
        $ouser_list = $ouser_list['data'];
        foreach ($ouser_list as $ok => &$ov){
            $ov['created'] = date('Y-m-d',$ov['created']);
        }
        $this->assign('warehouse',$warehouse);
        $this->assign('page',$page);
        $this->assign('ouser_list',$ouser_list);
        return $this->fetch('save_warehouse');
    }
    
    public function del_warehouse()
    {
        $result = array('err'=>'1','content' => '');
        $warehouse_id = input('post.id');
        
        $del_ouser = db('ouser')->where('warehouse_id',$warehouse_id)->delete();
        if ($del_ouser == false){
        	$result['content'] = '删除仓库用户失败！';
        	return $result;
        }

        $del_warehouse = db('warehouse')->where('id',$warehouse_id)->delete();
        if ($del_warehouse == false){
        	$result['content'] = '删除仓库失败！';
        	return $result;
        }
        $result['err'] = '0';
        $result['content'] = '删除成功！';
        return $result;
    }
    
    public function edit_warehouse()
    {
        $result = array('err' => '1','content' => '');
        $warehouse_info['id'] = input('post.warehouse_id');
        $warehouse_info['warehouse'] = input('post.warehouse_name');
        $rules = [
            'id' => 'require|number',
            'warehouse' => 'require|max:20'
        ];
        $message = [
            'id.require' => '参数缺失！',
            'id.number' => '参数错误',
            'warehouse.require' => '仓库名必须！',
            'warehouse.max' => '仓数名请控制在20以内！'
        ];
        $check_warehouse_info = $this->validate($warehouse_info, $rules,$message);
        if ($check_warehouse_info != 'true'){
            $result['content'] = $check_warehouse_info;
            return $result;
        }
        $warehouse = model('Warehouse');
        $edit_warehouse = $warehouse->saveWarehouse($warehouse_info);
        if ($warehouse == false){
            $result['content'] = '修改失败！';
            return $result;
        }
        $result['err'] = '0';
        $result['content'] = '修改成功！';
        return $result;
    }
    
    public function add_warehouse()
    {
        $result = array('err' => '1','content' => '');
        $warehouse_name = input('post.warehouse_name');
        if (trim($warehouse_name) == '' || strlen($warehouse_name) > 20){
            $result['content'] = '仓库名字数请控制在1~20之间';
            return $result;
        }
        $warehouse = model('Warehouse');
        $warehouse_info = array();
        $warehouse_info['warehouse'] = $warehouse_name;
        $warehouse_id = $warehouse->saveWarehouse($warehouse_info);
        if ($warehouse_id == false){
            $result['content'] = '添加仓库失败！';
            return $result;
        }
        $result['err'] = '0';
        $result['content'] = '添加成功！';
        $result['warehouse_id'] = $warehouse_id;
        return $result;
    }
    
    public function edit_ouser()
    {
        $result = array('err' => '1','content' => '');
        $ouser_info = array();
        $ouser_info['id'] = input('post.ouser_id');
        $ouser_info['user_name'] = input('post.ouser_name');
        $ouser_info['password'] = trim(input('post.password'));
        $rules = [
            'id' => 'require|number',
            'user_name' => 'require|max:20',
            'password' => 'require|max:20'
        ];
        $message = [
            'id.require' => '参数缺失！',
            'id.number' => '参数错误！',
            'user_name.require' => '用户名必须！',
            'user_name.max' => '用户名的字数请控制在20以内！',
            'password.require' => '请设置新密码！',
            'password.max' => '密码的字数请控制在20以内！'
        ];
        $check_ouser_info = $this->validate($ouser_info, $rules,$message);
        if ($check_ouser_info != 'true'){
            $result['content'] = $check_ouser_info;
            return $result;
        }
        $ouser = model('Ouser');
        $edit_ouser = $ouser->save_ouser($ouser_info);
        if ($edit_ouser == false){
            $result['content'] = '修改失败！';
            return $result;
        }
        $result['err'] = '0';
        $result['content'] = '修改成功！';
        return $result;
    }
    
    public function add_ouser()
    {
        $result = array('err' => '1','content' => '');
        $ouser_info = array();
        $ouser_info['warehouse_id'] = input('post.warehouse_id');
        $ouser_info['user_name'] = input('post.ouser_name');
        $rules = [
            'warehouse_id' => 'require|number',
            'user_name' => 'require|max:20'
        ];
        $message = [
            'warehouse_id.number' => '参数错误！',
            'warehouse_id.require' => '参数缺失！',
            'user_name.require' => '用户名必须！',
            'user_name.max' => '用户名的字数请控制在20以内!'
        ];
        $check_ouser_info = $this->validate($ouser_info, $rules,$message);
        if ($check_ouser_info != 'true'){
            $result['content'] = $check_ouser_info;
            return $result;
        }
        $ouser = model('Ouser');
        $ouser_id = $ouser->save_ouser($ouser_info);
        if ($ouser_id == false){
            $result['content'] = '添加用户失败！';
            return $result;
        }
        $result['data'] = [
            'ouser_id' => $ouser_id,
            'created' => date('Y-m-d',time())
        ];
        $result['err'] = '0';
        $result['content'] = '添加成功！';
        return $result;
    }
    
    public function del_ouser()
    {
        $result = array('err' => '1','content' =>'');
        $ouser_id = input('post.id');
        $del_ouser = db('ouser')->where('id',$ouser_id)->delete();
        if ($del_ouser == false){
            $result['content'] = '删除失败！';
            return $result;
        }
        $result['err'] = '0';
        $result['content'] = '删除成功！';
        return $result;
    }
    
    public function register_ouser_view()
    {
    	$keyword = trim(input('get.keyword'));
    	if (isset($keyword) && !empty($keyword)){
    		$user_list = db('ousertmp')->field(['id','user_name','warehouse_id','created'])->where('user_name','like','%'.$keyword.'%')->where('if_agree','0')->order('created')->paginate(12);
    	}else {
    		$user_list = db('ousertmp')->field(['id','user_name','warehouse_id','created'])->where('if_agree','0')->order('created')->paginate(12);
    	}
    	
    	$page = $user_list->render();
    	$model = model('Ouser');
    	$user_list = $user_list->toArray()['data'];
    	$user_list = $model->regulateOuserList($user_list);
    	$this->assign('lists',$user_list);
    	$this->assign('page',$page);
    	return $this->fetch('register_index');
    }
    
    public function register()
    {
    	$result = array('err'=>'1','content'=>'');
    	$if_agree_info = input('get.');
    	$rules = [
    			'if_agree' => 'require|number',
    			'user_id' => 'require|number'
    	];
    	$message = [
    			'if_agree.require' => '参数缺失！',
    			'if_agree.number' => '参数错误！',
    			'user_id.require' => '参数缺失！',
    			'user_id.number' => '参数错误！'
    	];
    	$check_agree_info = $this->validate($if_agree_info, $rules,$message);
    	if ($check_agree_info != 'true'){
    		$result['content'] = $check_agree_info;
    		return $result;
    	}
    	
    	
    	$model = model('Ouser');
    	$insert_ouser = $model->tmpToOuser($if_agree_info['user_id'],$if_agree_info['if_agree']);
    	if ($insert_ouser == false){
    		$result['content'] = '注册审批失败！';
    		return false;
    	}
    	$result['err'] = '0';
    	$result['content'] = '注册审批成功！';
    	return $result;
    }
    
  
}
